package com.tulink.yichutu.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mxixm.fastboot.weixin.module.message.WxMessage;
import com.mxixm.fastboot.weixin.module.message.WxUserMessage;
import com.mxixm.fastboot.weixin.service.WxApiService;
import com.mxixm.fastboot.weixin.util.WxMessageUtils;
import com.tulink.yichutu.entity.WxVipGoodsEntity;
import com.tulink.yichutu.service.WxVipGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.CharSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户缓存业务方法
 *
 * @author wanchaopeng
 */
@Slf4j
@Component
public class GoodsBiz {

    private static final String goodsCaches = "goodsCaches";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxVipGoodsService wxVipGoodsService;
    @Autowired
    private WxApiService wxApiService;

    public WxVipGoodsEntity getById(String goodsId) {
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(goodsCaches);
        Object obj = boundHashOperations.get(goodsId);
        if(obj == null) {
            return null;
        }
        return JSON.parseObject(obj.toString(), WxVipGoodsEntity.class);
    }

    public List<WxVipGoodsEntity> getGoods() {
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(goodsCaches);
        return Arrays.stream(boundHashOperations.values().toArray())
                .map(p -> JSON.parseObject(p.toString(), WxVipGoodsEntity.class))
                .filter(p -> p.getIndex() > 0)
                .sorted(Comparator.comparing(WxVipGoodsEntity::getIndex).reversed())
                .collect(Collectors.toList());
    }

    @PostConstruct
    public void initCache() {
        int count = 0;
        int total = 0;
        int pageSize = 500;
        log.info("开始初始化商品缓存...");
        redisTemplate.delete(goodsCaches);
        while (count < 1000) {
            Page<WxVipGoodsEntity> page = new Page<>(count, pageSize);
            page = wxVipGoodsService.page(page);
            List<WxVipGoodsEntity> vipGoodsEntities = page.getRecords();
            if (vipGoodsEntities.size() > 0) {
                BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(goodsCaches);
                Map<String, String> map = vipGoodsEntities.stream()
                        .collect(Collectors.toMap(WxVipGoodsEntity::getId, JSONObject::toJSONString, (p1, p2) -> JSONObject.toJSONString(p1)));
                boundHashOperations.putAll(map);
                total += vipGoodsEntities.size();
                log.info("已加载商品：{}", total);
            }
            if (vipGoodsEntities.size() < pageSize) {
                break;
            }
            count++;
        }
        log.info("初始化商品缓存完成：{}", total);
    }

    private String urlEncode(String url) {
        try {
            return URLEncoder.encode(url, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            log.error("urlEncode", e);
        }
        return url;
    }

    private Long getLongValue(Object obj) {
        try {
            if (obj instanceof Long) {
                return (Long) obj;
            } else if (obj instanceof Number) {
                return Long.valueOf(((Number) obj).longValue());
            } else if (obj instanceof String) {
                return Long.valueOf((String) obj);
            } else if (obj != null) {
                return Long.valueOf(obj.toString());
            }
        } catch (Exception ex) {

        }
        return null;
    }
}
